import { Button, Form, Input, message } from "antd";
import React, { useState } from "react";
import { LockOutlined, UserOutlined, MailOutlined } from "@ant-design/icons";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import "./register.css";
import { fetchsendVerification, fetchregister } from "../../store/modules/userStore";

const Register = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate(); // Add useNavigate hook
  const [form] = Form.useForm();
   const [isSendingCode, setIsSendingCode] = useState(false); 

  // 处理发送验证码
  const handleSendCode = async () => {
    try {
      // 验证邮箱和邀请码字段
      setIsSendingCode(true);
      const values = await form.validateFields(['email', 'inviteCode']);
   dispatch(fetchsendVerification(values)).then((res) => {
   
        if (res && res.code === 0) {
          message.success('验证码发送成功，请查收邮件');
        } else if (res && res.code === 1 && res.msg === "该邮箱已被注册") {
          // 如果后端返回邮箱已被注册的错误
          message.error('该邮箱已被注册，请使用其他邮箱或直接登录');
        } else {
          message.error(res?.msg || '验证码发送失败');
        }
      }).catch((error) => {
        message.error('发送验证码时出错');
      }).finally(() => {
        setIsSendingCode(false); // 无论成功失败，结束加载状态
      });
    } catch (error) {
      setIsSendingCode(false);
      message.error('请先填写正确的邮箱和邀请码');
    }
  };

  // 处理注册提交
  const onFinish = async (values) => {
    dispatch(fetchregister(values)).then((res) => {
      console.log(res.code);
      if (res && res.code === 0) {
        message.success('注册成功！即将跳转到登录页面');
        // 延迟1秒后跳转，让用户看到成功消息
        setTimeout(() => {
          navigate('/login'); // Assuming your login route is '/login'
        }, 1000);
      } else {
        message.error(res?.msg || '注册失败');
      
      }
    });
  };

  return (
    <div className="register-container">
      <Form
        form={form}
        onFinish={onFinish}
      >
        {/* 邮箱 */}
        <Form.Item
          name="email"
          rules={[
            { required: true, message: "请输入邮箱" },
            { type: 'email', message: '邮箱格式不正确' }
          ]}
        >
          <Input
            prefix={<MailOutlined />}
            placeholder="邮箱"
          />
        </Form.Item>

        {/* 邀请码 */}
        <Form.Item
          name="inviteCode"
          rules={[{ required: true, message: "请输入邀请码" }]}
        >
          <Input
            prefix={<LockOutlined />}
            placeholder="邀请码"
          />
        </Form.Item>

        {/* 发送验证码按钮 */}
         <Form.Item>
          <Button
            type="primary"
            onClick={handleSendCode}
            block
            loading={isSendingCode} // 添加加载状态
            disabled={isSendingCode} // 发送时禁用按钮
          >
            {isSendingCode ? '发送中...' : '发送验证码'}
          </Button>
        </Form.Item>

        {/* 验证码 */}
        <Form.Item
          name="verificationCode"
          rules={[{ required: true, message: "请输入验证码" }]}
        >
          <Input
            prefix={<LockOutlined />}
            placeholder="验证码"
          />
        </Form.Item>

        {/* 账号 */}
        <Form.Item
          name="identificationNumber"
          rules={[{ required: true, message: "请输入账号" }]}
        >
          <Input
            prefix={<UserOutlined />}
            placeholder="账号"
          />
        </Form.Item>

        {/* 密码 */}
        <Form.Item
          name="password"
          rules={[
            { required: true, message: "请输入密码" },
            { min: 6, message: "密码至少6位" }
          ]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="密码"
          />
        </Form.Item>

        {/* 注册按钮 */}
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            block
          >
            立即注册
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Register;